import React from "react";
import ReactDOM from "react-dom";

export default {
  counter: 0,
  layers: {},
  show() {
    let defProps = { // 默认传递给Component的属性
      onMessage: data => data && console.log('onMessage', data), // Component传递数据钩子
      onCancel: data => data && console.log('onCancel', data), // Component关闭或取消钩子
      onOk: data => data && console.log('onOk', data), // Component确认钩子
      history: null, // 其他react模型的路由history
      redux: null, // 其他react模型的redux相关的Provider和store：{Provider,store}
    };
    let [Component, props] = arguments;
    if (Component.type) { // 表明传的是react元素
      props = { ...defProps, ...Component.props, ...props };
      Component = Component.type;
    } else {
      props = { ...defProps, ...props };
    }

    let id = 'layer-react-' + this.counter++;
    let onCancel = data => {
      this.hide(id);
      props.onCancel(data);
    };
    let onOk = data => {
      this.hide(id);
      props.onOk(data);
    };
    let linkTo = url => {
      if (props.history) {
        this.hide(id);
        props.history.push(url);
      }
    };
    let newProps = { ...props, postMessage: props.onMessage, onCancel, onOk, linkTo, layerReactID: id };
    let reactEl = React.createElement(Component, newProps);
    let div = document.createElement("div");
    div.className = 'layer-react';
    document.body.appendChild(div);
    if (props.redux) {
      let { Provider, store } = props.redux;
      ReactDOM.render(<Provider store={store} children={reactEl}></Provider>, div);
    } else {
      ReactDOM.render(reactEl, div);
    }
    this.layers[id] = div;
    return reactEl;
  },
  hide() {
    if (arguments[0]) {
      let id = typeof arguments[0] == 'string' ? arguments[0] : arguments[0].props && arguments[0].props.id;
      if (id && this.layers[id]) {
        ReactDOM.unmountComponentAtNode(this.layers[id]);
        this.layers[id].remove();
      }
    } else {
      Object.keys(this.layers).forEach(key => {
        ReactDOM.unmountComponentAtNode(this.layers[key]);
        this.layers[key].remove();
      });
    }
  },
};